/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mrroman.linksender.filesender.authenticator;

import com.mrroman.linksender.filesender.server.*;
import java.util.HashMap;
import java.util.logging.Logger;

/**
 *
 * @author gorladam
 */
public class HttpBasicAuthenticator implements HttpAuthenticator {

    private HashMap<String, String> users;
    private Logger logger = Logger.getLogger(HttpBasicAuthenticator.class.getName());

    public HttpBasicAuthenticator() {
        users = new HashMap<String, String>();
    }

    @Override
    public void addUser(String user, String password) {
        String user_pass = HttpTools.base64encode(user + ":" + password);
        users.put(user_pass, user);
    }

    @Override
    public String getAuthenticate() {
        return "Basic realm=\""+HttpAuthenticator.defaultMessage+"\"";
    }

    @Override
    public String allowed(String authorization) {
        String result = null;
        String authorizationType = authorization.substring(0, authorization.indexOf(' '));
        if (authorizationType.toLowerCase().equals("basic")) {
            String authorizationData = authorization.substring(authorization.indexOf(' ') + 1);
            logger.finest("http basic authorization data: " + authorizationData);
            result = users.get(authorizationData);
        }
        return result;
    }

    @Override
    public String toString() {
        return HttpDigestAuthenticator.class.getSimpleName() +
                (users.keySet().size() < 1 ? "" : " " + users.keySet());
    }
}
